//
//  Rx+runloop.swift
//  SwiftCode
//
//  Created by yuhus on 2024/9/5.
//

import Foundation
import RxSwift

func runloop() {
  _ = Single.just(())
    .flatMap { _ -> Single<Bool> in
      return runloopPayState(.milliseconds(500))
    }
    .debug()
    .map { _ in () }
    .subscribe()
}

private func orderPayState(_ orderCode: Int) -> Single<OrderPayState> {
  if orderCode == 13 {
    return Single.just(.init(paid: true, shipped: true))
  }
  return Single.just(.init(paid: false, shipped: false))
}

private func fetchCoin() -> Single<Void> {
  print(#function, "fetchCoin")
  return Single.just(())
}

public struct OrderPayState: Codable {
  /// 是否支付成功
  public let paid: Bool
  /// 是否发货成功
  public let shipped: Bool
}

func runloopPayState(_ period: RxTimeInterval) -> Single<Bool> {
  Single<Bool>.create { single in
    var succeeded = false
    let disposable = Observable<Int>.interval(period, scheduler: MainScheduler.instance)
      .take(until: { succeeded || $0 == 5 })
      .flatMap { count in
        return orderPayState(count)
          .map(\.shipped)
          .do(onSuccess: { succeeded = $0 })
          .catchAndReturn(false)
      }
      .debug()
      .subscribe(onDisposed: {
        single(.success(succeeded))
      })
    
    return Disposables.create { disposable.dispose() }
  }
}
